from keras.datasets import imdb
import numpy as np
from keras import models
from keras import layers
import matplotlib.pyplot as plt

# number_words表示仅仅保留10000个最常的出现的单词，用于限制features的最大长度（即：results中列数最多10000）
(train_data, train_labels), (test_data, test_labels) = imdb.load_data(num_words=10000)
# train_data:(1,25000)

def vectorize_sequences(sequences, dim=10000):
    # sequences[0]:list 218
    # 行数i：sequence；列数j：单词出现频率
    results = np.zeros((len(sequences), dim))
    for i, j in enumerate(sequences):
        results[i, j] = 1
    return results


x_train = vectorize_sequences(train_data)
# (25000,10000):由0/1组成的二维矩阵
x_test = vectorize_sequences(test_data)
# (25000,10000):由0/1组成的二维矩阵


y_train = np.asarray(train_labels).astype('float32')
# (25000):由0/1组成的一维向量
y_test = np.asarray(test_labels).astype('float32')
# (25000):由0/1组成的一维向量
print("=========数据准备完成========")

model = models.Sequential()
model.add(layers.Dense(16, activation='relu', input_shape=(10000,)))
model.add(layers.Dense(16, activation='relu', ))
model.add(layers.Dense(1, activation='sigmoid', input_shape=(16,)))

model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy'])

history = model.fit(x_train, y_train, epochs=30, batch_size=512)
# 绘制损失
history_dict = history.history
loss_values = history_dict['loss']

epochs = range(1, len(loss_values) + 1)
plt.plot(epochs, loss_values, 'bo', label='Training Loss')
plt.xlabel('Epochs')
plt.ylabel('Loss')
plt.legend()
plt.show()

# 保存模型
mp = 'D:/code/DeepBloom-master/model/keras_gru_model.h5'
model.save(mp)